class Admin::ShopCategoriesController < AdminController
  def index
    @shop_categories = ShopCategory.where("parent_id = 0 OR parent_id IS NULL").order("sort ASC").page(params[:page]).per(params[:per])
  end

  def new
    @parent_category = ShopCategory.find params[:parent_id] if params[:parent_id].presence
    @shop_category = ShopCategory.new
  end

  def create
    @shop_category = ShopCategory.new shop_category_params
    if @shop_category.parent.blank?
      @shop_category.level = 1
    else
      if @shop_category.parent.level == 3
        redirect_to admin_shop_categories_path, notice: "不能再添加子分类！" and return
      else
        @shop_category.level = @shop_category.parent.level + 1
      end
    end
    if @shop_category.save
      redirect_to admin_shop_categories_path, notice: "保存成功！"
    else
      redirect_to admin_shop_categories_path, notice: "保存失败！"
    end
  end

  def edit
    @shop_category = ShopCategory.find params[:id]
    @parent_category = @shop_category.parent if @shop_category.parent.presence
  end

  def update
    @shop_category = ShopCategory.find params[:id]
    if @shop_category.update shop_category_params
      if @shop_category.parent.presence
        @shop_category.update_column("level", @shop_category.parent.level + 1)
      else
        @shop_category.update_column("level", 1)
      end
      redirect_to admin_shop_categories_path, notice: "更新成功！"
    else
      redirect_to admin_shop_categories_path, notice: "更新失败！"
    end
  end
  
  def destroy
    @shop_category = ShopCategory.find params[:id]
    if @shop_category.children.count > 0 || @shop_category.spus.count > 0
      redirect_to admin_shop_categories_path, notice: "存在子分类或商品，不能删除." and return
    end
    if @shop_category.destroy
      redirect_to admin_shop_categories_path, notice: "删除成功."
    else
      redirect_to admin_shop_categories_path, notice: "删除失败."
    end
  end

  private

  def shop_category_params
    params.require(:shop_category).permit(:name, :sort, :avatar, :published, :parent_id, :clearance)
  end
end
